package com.loyalove.zerone.auth.service.impl;

import java.util.Collection;
import java.util.HashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户数据获取Service
 *
 * @author loyal
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Override
  public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
    return mockUser(name);
  }

  /**
   * mock用户对象
   *
   * @param name 用户名
   * @return User
   */
  private User mockUser(String name) {
    /*用户判断*/
    if (!"admin".equals(name)) {
      return null;
    }

    Collection<GrantedAuthority> authorities = new HashSet<>();
    //用户所拥有的角色信息
    authorities.add(new SimpleGrantedAuthority("admin"));

    return new User("admin", passwordEncoder.encode("111111"), authorities);
  }
}
